package com.xavier.controller;

import cn.hutool.core.util.RandomUtil;
import com.xavier.annotation.PassLogin;
import com.xavier.constants.RedisKey;
import com.xavier.dto.UserLoginDTO;
import com.xavier.result.Result;
import com.xavier.service.IUserService;
import com.xavier.utils.PassWordUtils;
import com.xavier.utils.RedisUtil;
import com.xavier.utils.UserUtil;
import com.xavier.vo.UserInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 请求处理层-登录管理类
 *
 * @author Xavier
 * @version 1.0
 */
@Slf4j
@RequestMapping
@RestController
@Tag(name = "登录管理接口")
public class LoginController extends CommonController {

    @Resource
    private IUserService userService;

    @Operation(summary = "用户登录", description = "用户登录")
    @PostMapping("login")
    @PassLogin
    public Result<String> login(@Validated @RequestBody UserLoginDTO dto) {
        dto.setUserPwd(PassWordUtils.decryptUserPwd(dto.getUserPwd()));
        UserInfoVO userInfoVO = userService.login(dto);
        UserUtil.setRedisUser(userInfoVO);
        return Result.success(userInfoVO.getToken());
    }

    @Operation(summary = "获取登录用户信息", description = "获取登录用户信息，有缓存")
    @GetMapping("getInfo")
    public Result<UserInfoVO> getInfo() {
        return Result.success(getUser());
    }

    @Operation(summary = "用户退出", description = "用户退出")
    @GetMapping("logout")
    public Result logout() {
        RedisUtil.delete(RedisKey.getTokenKey(UserUtil.getToken()));
        return Result.success();
    }


}
